<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <script type="text/javascript" src="../public/cdn/axios/1.0.0/axios.min.js"></script>
    </head>

    <!--
        axios是异步发起请求的，
    -->

    <script>
        // 演示get请求
        axios
            .get("json/data.json")
            .then((resp) => {
                // resp不是直接的返回结果，而是响应状态信息
                console.log(resp);
                // resp.data才是真正的返回结果
                console.log(resp.data);
            })
            .catch((err) => {
                // 请求失败或者then逻辑出错时，会回调到catch
                console.log("err.response.status:" + err.response.status);
                console.log("err.response.statusText:" + err.response.statusText);
            });

        // 演示POST请求 Content-Type: application/json
        let data = {uname: "dingding", upwd: 123456};
        axios
        .post("json/data.json", JSON.stringify(data))
        .then((resp) => {
                console.log(resp.data);
            })
        .catch((err) => {
            console.log("err.response.status:" + err.response.status);
            console.log("err.response.statusText:" + err.response.statusText);
        });

        // Content-Type: multipart/form-data（常用于表单提交（图片上传、文件上传））
        let formData = new FormData();
        for (let key in data) {
            formData.append(key, data[key]);
        }
        axios
            .post("json/data.json", formData)
            .then((resp) => {
                console.log(resp.data);
            })
            .catch((err) => {
                console.log("err.response.status:" + err.response.status);
                console.log("err.response.statusText:" + err.response.statusText);
            });
        // Content-Type: application/x-www-form-urlencoded
        axios
            .post("json/data.json", "uname=test&upwd=123456")
            .then((resp) => {
                console.log(resp.data);
            })
            .catch((err) => {
                console.log("err.response.status:" + err.response.status);
                console.log("err.response.statusText:" + err.response.statusText);
            });

        // 并发请求用到了axios的两个方法：axios.all('参数是一个数组')、axios.spread('回调函数')
        axios.all([axios.get("json/data.json"), axios.get("json/data.json")]).then(
            axios.spread((resp1, resp2) => {
                console.log(resp1, resp2);
            })
        );
    </script>
    <body>
    </body>
</html>
